package com.jinhuhang.u2.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.entity.BankBranch;
import com.jinhuhang.u2.listener.Listener;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.adapter.rxjava.HttpException;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by OnionMac on 17/9/13.
 */

public class UtilsCollection {
    private static String patten = "^(?![A-Z]+$)(?![a-z]+$)(?!\\d+$)(?![\\W_]+$)\\S{6,16}$";

    public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";

    /**
     * 验证手机号（精确）
     *
     * @param string 待验证文本
     * @return {@code true}: 匹配<br>{@code false}: 不匹配
     */
    public static boolean isMobileExact(String string) {
        return isMatch(REGEX_MOBILE_EXACT, string);
    }

    public static boolean check(String phone) {
        Pattern pattern = Pattern.compile(patten);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    /**
     * string是否匹配regex
     *
     * @param regex  正则表达式字符串
     * @param string 要匹配的字符串
     * @return {@code true}: 匹配<br>{@code false}: 不匹配
     */
    private static boolean isMatch(String regex, String string) {
        return !StringUtils.isEmpty(string) && Pattern.matches(regex, string);
    }

    /**
     * 验证码倒计时
     *
     * @param time
     * @return
     */
    public static Observable<String> countdown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(increaseTime -> (countTime - increaseTime.intValue()) + "")
                .take(countTime + 1);
    }

    public static Dialog getAlertDialog(Activity activity){
        /**
         * 窗体
         */
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        /**
         * 自定义idialog
         */
        Dialog alertDialog = new Dialog(activity,R.style.capitaldialog);
        alertDialog.setContentView(LayoutInflater.from(activity).inflate(R.layout.bank_dialog_time,null,false));
        /**
         * 拿到windows对象
         */
        Window window = alertDialog.getWindow();
        final WindowManager.LayoutParams lp=window.getAttributes();
        //设置居中
        window.setGravity(Gravity.CENTER);
        lp.y = Utils.dp2px(MyApplication.getContext(),-50);
        lp.alpha=1.0f;
        lp.width = (int) (display.getWidth() * 0.65);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.getWindow().setAttributes(lp);
        return alertDialog;
    }

    /**
     * MD5加密
     * @param source
     * @return
     */
    public static String encodeToMd5(String source) {
        if (source == null)
            return null;

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");

            char hexDigits[] = {
                    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                    'e', 'f'};

            byte[] strTemp = source.getBytes("utf-8");
            mdTemp.update(strTemp);

            byte[] md = mdTemp.digest();
            int k = 0;
            int j = md.length;
            char str[] = new char[j * 2];

            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void errorUtil(Throwable throwable) {
        if(throwable instanceof ConnectException){
            Toast.makeText(MyApplication.getContext(),"服务器未响应", Toast.LENGTH_SHORT).show();
        }else if(throwable instanceof HttpException){
            Toast.makeText(MyApplication.getContext(),"服务器未响应", Toast.LENGTH_SHORT).show();
        }else if(throwable instanceof TimeoutException){
            Toast.makeText(MyApplication.getContext(),"服务器未响应", Toast.LENGTH_SHORT).show();
        }else if(throwable instanceof SocketTimeoutException){
            Toast.makeText(MyApplication.getContext(),"服务器未响应", Toast.LENGTH_SHORT).show();
        }else if(throwable instanceof UnknownHostException){
            Toast.makeText(MyApplication.getContext(),"服务器未响应", Toast.LENGTH_SHORT).show();
        }
    }

    public static String connectString(String... str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length; i++) {
            sb.append(str[i]);
        }

        return sb.toString();
    }

    /**
     * 提供精确加法计算的add方法
     *
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
    public static double add(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确减法运算的sub方法
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     */
    public static double sub(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确乘法运算的mul方法
     *
     * @param value1 被乘数
     * @param value2 乘数
     * @return 两个参数的积
     */
    public static double mul(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 提供精确的除法运算方法div
     *
     * @param value1 被除数
     * @param value2 除数
     * @param scale  精确范围
     * @return 两个参数的商
     * @throws IllegalAccessException
     */
    public static double div(double value1, double value2, int scale) throws IllegalAccessException {
        //如果精确范围小于0，抛出异常信息
        if (scale < 0) {
            throw new IllegalAccessException("精确度不能小于0");
        }
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.divide(b2, scale).doubleValue();
    }

    public static AlertDialog getSlectDialog(Activity activity,String title,String message,String left,String right,Listener.OnNormalAlertDialogChooseClickListener listener){
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
        builder.setTitle(title);
        builder.setMessage(message);;
        builder.setNegativeButton(left, (dialog, which) -> {
            if(listener != null)
            listener.onLeft();
        });
        builder.setPositiveButton(right, (dialog, which) -> {
            if(listener != null)
            listener.onRight();
        });
        AlertDialog alertDialog = builder.create();
        return alertDialog;
    }


    public static AlertDialog getSingleDialog(Activity activity,String title,String message,String left,Listener.OnNormalAlertDialogSingleClickListener listener){
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
        builder.setTitle(title);
        builder.setMessage(message);;
        builder.setNegativeButton(left, (dialog, which) -> {
            if(listener != null)
            listener.singleClick();
        });
        AlertDialog alertDialog = builder.create();
        return alertDialog;
    }

    public static int getColor(Context context,int color){
        return context.getResources().getColor(color);
    }


    public static BankBranch getBankBranch(String abc){
        Map<String,BankBranch> map = new HashMap<>();
        map.put("ABC",new BankBranch("农业银行",R.drawable.nongye));
        map.put("BCOM",new BankBranch("交通银行",R.drawable.jiaotong));
        map.put("BOC",new BankBranch("中国银行",R.drawable.zhongguo));
        map.put("CCB",new BankBranch("建设银行",R.drawable.jiansheng));
        map.put("CEB",new BankBranch("光大银行",R.drawable.guangda));
        map.put("CIB",new BankBranch("兴业银行",R.drawable.xingye));
        map.put("CITIC",new BankBranch("中信银行",R.drawable.zhongxin));
        map.put("CMB",new BankBranch("招商银行",R.drawable.zhaoshang));
        map.put("CMBC",new BankBranch("民生",R.drawable.minsheng));
        map.put("GDB",new BankBranch("广发银行",R.drawable.guangfa));
        map.put("HXB",new BankBranch("华夏银行",R.drawable.huaxia));
        map.put("ICBC",new BankBranch("工商银行",R.drawable.gongshang));
        map.put("PAB",new BankBranch("平安银行",R.drawable.pingan));
        map.put("PSBC",new BankBranch("中国邮政储蓄",R.drawable.youzheng));
        map.put("SHB",new BankBranch("上海银行",R.drawable.shanghai));
        map.put("SPDB",new BankBranch("浦发银行",R.drawable.pufa));
        return map.get(abc);
    }

    public static boolean isNumber(String str)
    {
        Pattern pattern= Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
        java.util.regex.Matcher match=pattern.matcher(str);
        if(match.matches()==false)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    public static float[] percentageArithmetic(float first, float second, float three) {
        float[] temp = {first,second,three};
        float[] air = {3};

        for (int i = 0; i < temp.length; i++) {
            if(temp[i] > 359){
                air[i] = 358;
            }

            if(temp[i] < 1 && temp[i] > 0){
                temp[i] = 1;
            }
        }

        return temp;
    }

    /**
     * 防止double过大使用科学计数法
     * @param value
     * @return
     */
    public static String formatFloatNumber(double value) {
        if(value != 0.00){
            java.text.DecimalFormat df = new java.text.DecimalFormat("########.00");
            return df.format(value);
        }else{
            return "0.00";
        }

    }
    public static String formatNumber(double value) {
        if(value != 0.00){
            BigDecimal   b   =   new   BigDecimal(value);
            double   f1   =   b.setScale(2,   BigDecimal.ROUND_DOWN).doubleValue();
            return String.valueOf(f1);
        }else{
            return "0.00";
        }

    }
    public static String formatNumber1(double value) {
        if(value != 0.00){
            java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
            return df.format(value);
        }else{
            return "0.00";
        }

    }
}
